import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { gsap } from 'gsap';
import './Gallery.css';
import FabricCanvas from '../components/FabricCanvas';

interface CanvasImage {
  id: string;
  src: string;
  x: number;
  y: number;
  width: number;
  height: number;
  rotation: number;
  scale: number;
  selected: boolean;
}

const Gallery: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [images, setImages] = useState<CanvasImage[]>([]);
  const [activeTool, setActiveTool] = useState<string>('select');
  const [selectedImageId, setSelectedImageId] = useState<string | null>(null);
  const [layers, setLayers] = useState<any[]>([]);
  const [showLayersPanel, setShowLayersPanel] = useState<boolean>(true);
  const [isLoadingImage, setIsLoadingImage] = useState<boolean>(false);
  const [brushColor, setBrushColor] = useState<string>('#000000');
  const [brushWidth, setBrushWidth] = useState<number>(1);
  const [eraseColor, setEraseColor] = useState<string>('#ffffff');
  const [eraseWidth, setEraseWidth] = useState<number>(20);
  const [showBrushColorDropdown, setShowBrushColorDropdown] = useState<boolean>(false);
  const [showEraseColorDropdown, setShowEraseColorDropdown] = useState<boolean>(false);
  
  // 颜色选项
  const brushColors = [
    { value: '#000000', name: '黑色' },
    { value: '#ffffff', name: '白色' },
    { value: '#ff0000', name: '红色' },
    { value: '#00ff00', name: '绿色' },
    { value: '#0000ff', name: '蓝色' },
    { value: '#ffff00', name: '黄色' },
    { value: '#ff00ff', name: '紫色' },
    { value: '#00ffff', name: '青色' },
    { value: '#ffa500', name: '橙色' },
    { value: '#808080', name: '灰色' }
  ];
  
  const eraseColors = [
    { value: '#ffffff', name: '白色' },
    { value: '#000000', name: '黑色' }
  ];
  const canvasRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const fabricCanvasRef = useRef<any>(null);
  
  // GSAP 动画 refs
  const mainContentRef = useRef<HTMLDivElement>(null);
  const toolbarRef = useRef<HTMLDivElement>(null);
  const canvasContainerRef = useRef<HTMLDivElement>(null);
  const layersPanelRef = useRef<HTMLDivElement>(null);

  // 获取传递的图片数据
  const imageToEdit = location.state?.imageToEdit;
  const prompt = location.state?.prompt || '';
  const format = location.state?.format || '图片生成';
  const aspectRatio = location.state?.aspectRatio || '瑜伽';

  // 禁止页面滚动
  useEffect(() => {
    // 保存原始样式
    const originalBodyOverflow = document.body.style.overflow;
    const originalHtmlOverflow = document.documentElement.style.overflow;
    const mainContentWrapper = document.querySelector('.main-content-wrapper') as HTMLElement;
    const originalWrapperOverflow = mainContentWrapper?.style.overflow;
    
    // 禁止滚动
    document.body.style.overflow = 'hidden';
    document.documentElement.style.overflow = 'hidden';
    if (mainContentWrapper) {
      mainContentWrapper.style.overflow = 'hidden';
    }
    
    // 组件卸载时恢复滚动
    return () => {
      document.body.style.overflow = originalBodyOverflow;
      document.documentElement.style.overflow = originalHtmlOverflow;
      if (mainContentWrapper) {
        mainContentWrapper.style.overflow = originalWrapperOverflow || '';
      }
    };
  }, []);

  // 点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.color-dropdown')) {
        setShowBrushColorDropdown(false);
        setShowEraseColorDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // GSAP 入场动画
  useEffect(() => {
    const tl = gsap.timeline();
    
    // 设置初始状态
    gsap.set(mainContentRef.current, { opacity: 0, y: 20 });
    gsap.set(toolbarRef.current, { opacity: 0, y: -20, scale: 0.9 });
    gsap.set(canvasContainerRef.current, { opacity: 0, y: 30, scale: 0.95 });
    if (showLayersPanel && layersPanelRef.current) {
      gsap.set(layersPanelRef.current, { opacity: 0, x: 20, scale: 0.95 });
    }

    // 执行动画序列
    tl.to(mainContentRef.current, {
      opacity: 1,
      y: 0,
      duration: 0.6,
      ease: "power2.out"
    })
    .to(toolbarRef.current, {
      opacity: 1,
      y: 0,
      scale: 1,
      duration: 0.5,
      ease: "back.out(1.7)"
    }, "-=0.4")
    .to(canvasContainerRef.current, {
      opacity: 1,
      y: 0,
      scale: 1,
      duration: 0.5,
      ease: "power2.out"
    }, "-=0.3")
    .to(layersPanelRef.current, {
      opacity: 1,
      x: 0,
      scale: 1,
      duration: 0.4,
      ease: "power2.out"
    }, "-=0.2");

    return () => {
      tl.kill();
    };
  }, [showLayersPanel]);

  // 处理文件上传
  const handleFileUpload = useCallback((files: FileList) => {
    if (fabricCanvasRef.current) {
      (fabricCanvasRef.current as any).handleFileUpload(files);
    }
  }, []);

  // 处理拖拽上传
  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileUpload(files);
    }
  }, [handleFileUpload]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
  }, []);

  // 键盘快捷键处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Delete' || e.key === 'Backspace') {
        if (fabricCanvasRef.current) {
          (fabricCanvasRef.current as any).deleteSelected();
        }
      } else if (e.key === 'Escape') {
        setSelectedImageId(null);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  // 更新图层列表
  const updateLayers = useCallback(() => {
    if (fabricCanvasRef.current && fabricCanvasRef.current.getCanvas) {
      try {
        const canvas = fabricCanvasRef.current.getCanvas();
        const objects = canvas.getObjects();
        const activeObject = canvas.getActiveObject();
        
        const layerList = objects.map((obj: any, index: number) => {
          // 获取对象预览图
          let preview = null;
          try {
            if (obj.type === 'image') {
              // 对于图片对象，使用 toDataURL 生成预览
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              const size = 40; // 预览图大小
              canvas.width = size;
              canvas.height = size;
              
              // 计算缩放比例
              const scale = Math.min(size / obj.width, size / obj.height);
              const scaledWidth = obj.width * scale;
              const scaledHeight = obj.height * scale;
              const offsetX = (size - scaledWidth) / 2;
              const offsetY = (size - scaledHeight) / 2;
              
              if (ctx) {
                ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
                ctx.fillRect(0, 0, size, size);
                
                // 绘制图片
                ctx.drawImage(
                  obj.getElement(), 
                  offsetX, offsetY, scaledWidth, scaledHeight
                );
                
                preview = canvas.toDataURL('image/png', 0.8);
              }
            } else if (obj.type === 'path' || obj.type === 'group') {
              // 对于路径和组对象，使用 toDataURL 生成预览
              preview = obj.toDataURL({ 
                format: 'png', 
                quality: 0.6,
                multiplier: 0.5
              });
            }
          } catch (e) {
            // 静默处理预览生成失败
          }
          
          const isSelected = obj === activeObject;
          
          return {
            id: obj.name || `layer-${index}`,
            name: obj.name || `图层 ${index + 1}`,
            type: obj.type || 'unknown',
            visible: obj.visible !== false,
            selected: isSelected,
            preview: preview,
            object: obj
          };
        });
        
        setLayers(layerList);
      } catch (error) {
        console.error('更新图层失败:', error);
      }
    }
  }, []);

  // 初始化时更新图层
  useEffect(() => {
    const timer = setTimeout(() => {
      updateLayers();
    }, 100);
    return () => clearTimeout(timer);
  }, [updateLayers]);

  // 处理传递过来的图片，自动加载到画布
  useEffect(() => {
    if (imageToEdit && fabricCanvasRef.current) {
      setIsLoadingImage(true);
      
      // 创建一个临时的 File 对象来模拟文件上传
      const loadImageToCanvas = async () => {
        try {
          // 将 base64 或 URL 转换为 File 对象
          let file: File;
          
          if (imageToEdit.startsWith('data:')) {
            // 处理 base64 数据
            const response = await fetch(imageToEdit);
            const blob = await response.blob();
            file = new File([blob], 'edit-image.png', { type: 'image/png' });
          } else {
            // 处理 URL
            const response = await fetch(imageToEdit);
            const blob = await response.blob();
            file = new File([blob], 'edit-image.png', { type: 'image/png' });
          }
          
          // 创建 FileList 对象
          const fileList = {
            0: file,
            length: 1,
            item: (index: number) => index === 0 ? file : null,
            [Symbol.iterator]: function* () {
              yield file;
            }
          } as FileList;
          
          // 调用文件上传处理（现在会等待图片加载完成）
          await handleFileUpload(fileList);
          setIsLoadingImage(false);
          
        } catch (error) {
          console.error('加载图片到画布失败:', error);
          setIsLoadingImage(false);
        }
      };
      
      // 延迟一点时间确保 FabricCanvas 组件已经初始化
      const timer = setTimeout(loadImageToCanvas, 300);
      return () => clearTimeout(timer);
    }
  }, [imageToEdit, handleFileUpload, updateLayers]);

  // 处理图片选择
  const handleImageSelect = useCallback((imageId: string) => {
    setSelectedImageId(imageId);
  }, []);

  // 选择图层
  const handleLayerSelect = useCallback((layerId: string) => {
    if (fabricCanvasRef.current && fabricCanvasRef.current.getCanvas) {
      try {
        const canvas = fabricCanvasRef.current.getCanvas();
        const layer = layers.find(l => l.id === layerId);
        if (layer && layer.object) {
          canvas.setActiveObject(layer.object);
          canvas.renderAll();
          setSelectedImageId(layerId);
          
          // 选择后立即更新图层列表以反映选中状态
          setTimeout(() => {
            updateLayers();
          }, 50);
        }
      } catch (error) {
        console.error('选择图层失败:', error);
      }
    }
  }, [layers, updateLayers]);

  // 切换图层可见性
  const toggleLayerVisibility = useCallback((layerId: string) => {
    if (fabricCanvasRef.current && fabricCanvasRef.current.getCanvas) {
      try {
        const canvas = fabricCanvasRef.current.getCanvas();
        const layer = layers.find(l => l.id === layerId);
        if (layer && layer.object) {
          layer.object.set('visible', !layer.object.visible);
          canvas.renderAll();
          updateLayers();
        }
      } catch (error) {
        console.error('切换图层可见性失败:', error);
      }
    }
  }, [layers, updateLayers]);

  // 处理图片删除
  const handleImageDelete = useCallback(() => {
    if (fabricCanvasRef.current) {
      (fabricCanvasRef.current as any).deleteSelected();
    }
  }, []);


  // 处理保存 - 将画布图片带回 Generate 页面
  const handleSave = useCallback(() => {
    if (fabricCanvasRef.current) {
      try {
        // 使用 FabricCanvas 组件暴露的 toDataURL 方法
        const dataURL = fabricCanvasRef.current.toDataURL({
          format: 'png',
          quality: 1,
          multiplier: 1
        });
        
        if (dataURL) {
          // 跳转到 Generate 页面，传递画布图片数据
          navigate('/generate', {
            state: {
              uploadedImage: dataURL,
              prompt: prompt,
              selectedFeature: format,
              selectedBusiness: aspectRatio
            }
          });
        } else {
          console.error('无法生成图片数据');
        }
      } catch (error) {
        console.error('保存失败:', error);
      }
    }
  }, [navigate, prompt, format, aspectRatio]);

  // 处理下载 - 直接下载到本地
  const handleDownload = useCallback(() => {
    if (fabricCanvasRef.current) {
      try {
        // 使用 FabricCanvas 组件暴露的 toDataURL 方法
        const dataURL = fabricCanvasRef.current.toDataURL({
          format: 'png',
          quality: 1,
          multiplier: 1
        });
        
        if (dataURL) {
          // 创建下载链接
          const link = document.createElement('a');
          link.download = `canvas-${Date.now()}.png`;
          link.href = dataURL;
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          console.error('无法生成图片数据');
        }
      } catch (error) {
        console.error('下载失败:', error);
      }
    }
  }, []);

  // 处理清空
  const handleClear = useCallback(() => {
    if (fabricCanvasRef.current) {
      try {
        // 使用 FabricCanvas 组件暴露的 clear 方法
        fabricCanvasRef.current.clear();
        
        // 清空图片数据
        setImages([]);
        setSelectedImageId(null);
        setLayers([]);
        // 画布已清空（包括画笔内容）
      } catch (error) {
        console.error('清空失败:', error);
        // 备用方案：直接清空状态
        setImages([]);
        setSelectedImageId(null);
        setLayers([]);
      }
    }
  }, []);

  return (
    <div ref={mainContentRef} className="main-content">
      {/* 工具栏 */}
      <div ref={toolbarRef} className="canvas-toolbar">
        <div className="tool-buttons">
        <button
            className="tool-btn"
            onClick={() => fileInputRef.current?.click()}
            title="上传图片"
          >
            上传图片
          </button>
          <button
            className={`tool-btn ${activeTool === 'select' ? 'active' : ''}`}
            onClick={() => setActiveTool('select')}
            title="选择"
          >
            选择
          </button>
          <button
            className={`tool-btn ${activeTool === 'brush' ? 'active' : ''}`}
            onClick={() => setActiveTool('brush')}
            title="画笔"
          >
            画笔
          </button>
          <button
            className={`tool-btn ${activeTool === 'erase' ? 'active' : ''}`}
            onClick={() => setActiveTool('erase')}
            title="涂抹"
          >
            涂抹
          </button>
          <button
            className={`tool-btn ${activeTool === 'crop' ? 'active' : ''}`}
            onClick={() => setActiveTool('crop')}
            title="裁剪"
          >
            裁剪
          </button>
          
          {/* 画笔颜色选择 - 只在画笔模式下显示 */}
          {activeTool === 'brush' && (
            <div className="color-picker">
              <label>颜色:</label>
              <div className="color-dropdown">
                <button
                  className="color-dropdown-trigger"
                  onClick={() => setShowBrushColorDropdown(!showBrushColorDropdown)}
                >
                  <div 
                    className="color-preview"
                    style={{ backgroundColor: brushColor }}
                  />
                  <span className="color-name">
                    {brushColors.find(c => c.value === brushColor)?.name}
                  </span>
                  <span className="color-arrow">▼</span>
                </button>
                
                {showBrushColorDropdown && (
                  <div className="color-dropdown-menu">
                    {brushColors.map((color) => (
                      <button
                        key={color.value}
                        className={`color-dropdown-item ${brushColor === color.value ? 'active' : ''}`}
                        onClick={() => {
                          setBrushColor(color.value);
                          setShowBrushColorDropdown(false);
                        }}
                      >
                        <div 
                          className="color-preview"
                          style={{ backgroundColor: color.value }}
                        />
                        <span className="color-name">{color.name}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
          
          {/* 涂抹颜色选择 - 只在涂抹模式下显示 */}
          {activeTool === 'erase' && (
            <div className="color-picker">
              <label>颜色:</label>
              <div className="color-dropdown">
                <button
                  className="color-dropdown-trigger"
                  onClick={() => setShowEraseColorDropdown(!showEraseColorDropdown)}
                >
                  <div 
                    className="color-preview"
                    style={{ backgroundColor: eraseColor }}
                  />
                  <span className="color-name">
                    {eraseColors.find(c => c.value === eraseColor)?.name}
                  </span>
                  <span className="color-arrow">▼</span>
                </button>
                
                {showEraseColorDropdown && (
                  <div className="color-dropdown-menu">
                    {eraseColors.map((color) => (
                      <button
                        key={color.value}
                        className={`color-dropdown-item ${eraseColor === color.value ? 'active' : ''}`}
                        onClick={() => {
                          setEraseColor(color.value);
                          setShowEraseColorDropdown(false);
                        }}
                      >
                        <div 
                          className="color-preview"
                          style={{ backgroundColor: color.value }}
                        />
                        <span className="color-name">{color.name}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
          
          {/* 画笔宽度选择 - 只在画笔模式下显示 */}
          {activeTool === 'brush' && (
            <div className="brush-size">
              <label>粗细:</label>
              <input
                type="range"
                min="1"
                max="20"
                value={brushWidth}
                onChange={(e) => setBrushWidth(Number(e.target.value))}
                className="brush-slider"
              />
              <span className="brush-size-value">{brushWidth}px</span>
            </div>
          )}
          
          {/* 涂抹宽度选择 - 只在涂抹模式下显示 */}
          {activeTool === 'erase' && (
            <div className="brush-size">
              <label>粗细:</label>
              <input
                type="range"
                min="20"
                max="60"
                value={eraseWidth}
                onChange={(e) => setEraseWidth(Number(e.target.value))}
                className="brush-slider"
              />
              <span className="brush-size-value">{eraseWidth}px</span>
            </div>
          )}
          
 
          {selectedImageId && (
            <button
              className="tool-btn delete-btn"
              onClick={handleImageDelete}
              title="删除"
            >
              删除
            </button>
          )}
          <button
            className="tool-btn save-btn"
            onClick={handleSave}
            title="保存到生成页面"
          >
            保存
          </button>
          <button
            className="tool-btn"
            onClick={handleClear}
            title="清空"
          >
            清空
          </button>
          <button
            className="tool-btn download-btn"
            onClick={handleDownload}
            title="下载到本地"
          >
            下载
          </button>
        </div>

        {/* 隐藏的文件输入 */}
        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept="image/*"
          onChange={(e) => {
            if (e.target.files) {
              handleFileUpload(e.target.files);
            }
          }}
          style={{ display: 'none' }}
        />
      </div>

      {/* 画布区域 */}
      <div ref={canvasContainerRef} className="canvas-container">
        <div 
          className="canvas-area"
          ref={canvasRef}
          onDrop={handleDrop}
          onDragOver={handleDragOver}
        >
          <FabricCanvas
            images={images}
            onImagesChange={(newImages) => {
              setImages(newImages);
              updateLayers();
            }}
            activeTool={activeTool}
            onImageSelect={handleImageSelect}
            onLayersChange={updateLayers}
            brushColor={activeTool === 'brush' ? brushColor : eraseColor}
            brushWidth={activeTool === 'brush' ? brushWidth : eraseWidth}
            ref={fabricCanvasRef}
          />
          
          {/* 加载指示器 */}
          {isLoadingImage && (
            <div className="upload-overlay">
              <div className="upload-spinner">
                <div className="upload-loading-indicator"></div>
                <p>正在加载图片到画布...</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 图层面板 */}
      {showLayersPanel && (
        <div ref={layersPanelRef} className="layers-panel">
          <div className="layers-header">
            <h3>图层</h3>
            <button 
              className="toggle-panel-btn"
              onClick={() => setShowLayersPanel(false)}
              title="关闭图层面板"
            >
              ×
            </button>
          </div>
          <div className="layers-list">
            {layers.length === 0 ? (
              <div className="no-layers">暂无图层</div>
            ) : (
              layers.map((layer) => (
                <div
                  key={layer.id}
                  className={`layer-item ${layer.selected ? 'selected' : ''}`}
                  onClick={() => handleLayerSelect(layer.id)}
                >
                  <div className="layer-preview">
                    {layer.preview && layer.preview.startsWith('data:') ? (
                      <img 
                        src={layer.preview} 
                        alt={layer.name}
                        className="layer-thumbnail"
                        onError={(e) => {
                          e.currentTarget.style.display = 'none';
                        }}
                      />
                    ) : (
                      <div className="layer-placeholder">
                        {layer.type === 'image' ? '🖼️' : layer.type === 'path' ? '✏️' : '📄'}
                      </div>
                    )}
                  </div>
                  <div className="layer-info">
                    <span className="layer-name">{layer.name}</span>
                    <span className="layer-type">({layer.type})</span>
                  </div>
                  <div className="layer-controls">
                    <button
                      className="visibility-btn"
                      onClick={(e) => {
                        e.stopPropagation();
                        toggleLayerVisibility(layer.id);
                      }}
                      title={layer.visible ? '隐藏图层' : '显示图层'}
                    >
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                        {layer.visible ? (
                          <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                        ) : (
                          <path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/>
                        )}
                      </svg>
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      )}

      {/* 显示图层面板按钮 */}
      {!showLayersPanel && (
        <button 
          className="show-layers-btn"
          onClick={() => setShowLayersPanel(true)}
          title="显示图层面板"
        >
          📋
        </button>
      )}
    </div>
  );
};

export default Gallery;
